package com.example.demo.utils;

import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

import static com.alibaba.fastjson.util.TypeUtils.castToString;


public class JSONArray extends ArrayList {

    public JSONArray() {
    }

    public JSONArray(Collection c) {
        super(c);
    }

    public JSONObject getJSONObject(int index) {
        Object value = this.get(index);
        if (value instanceof JSONObject) {
            return (JSONObject)value;
        } else {
            try {
                return value instanceof Map ? new JSONObject((Map)value) : JSONUtil.parseObject(JSONUtil.toJson(value));
            } catch (IOException e) {
                throw new IllegalArgumentException("Serialize to json failed for index : " + index + " in value \n" + value, e);
            }
        }
    }

    public JSONArray getJSONArray(int index) {
        Object value = this.get(index);
        if (value instanceof JSONArray) {
            return (JSONArray)value;
        } else {
            try {
                return value instanceof List ? new JSONArray((List)value) : JSONUtil.parseArray(JSONUtil.toJson(value));
            } catch (IOException e) {
                throw new IllegalArgumentException("Serialize to json array failed for index : " + index + " in value \n" + value, e);
            }
        }
    }

    public String toJSONString() {
        try {
            return JSONUtil.toJson(this);
        } catch (IOException e) {
            throw new IllegalArgumentException("Serialize to json failed  : " + this, e);
        }
    }

    public String getString(int index) {
        Object value = get(index);

        return castToString(value);
    }

}
